 /*
 *  *Target：创建共享内存并将结构体中的数据写入共享内存
 *  *Author：朱家林
 *  *Date：2017.7.18
 *    
 */
#include "project.h"
#include "sem.h"

void shm_create()
{
	int shmid;
	key_t key;
	key = ftok("/",'c');
	if(key < 0)
	{
		perror("shm:fail to ftok");
		exit(-1);
	}
	fisrt_init_sem(&semid, &key);//初始化信号量
	init_sem(semid, 0, 1);

	shmid = shmget(key, sizeof(myEnv),IPC_CREAT | IPC_EXCL | 0777);
	if(shmid < 0)
	{
		if (errno == EEXIST)
		{
			shmid = shmget(key,0,0);
		}
		else
		{
			perror("fail to shmget");
			exit(-1);
		}
	}
	if((pmyEnv = (sendEnv *)shmat(shmid,NULL,0)) ==(sendEnv *)-1 )
	{
		perror("fail to shmmat");
		exit(-1);
	}
}

void *pthread_shm_refresh()
{

	shm_create();
	printf("shm_create success!!!\n");

	int i = 0;
	while(1)
	{
		
		pthread_mutex_lock(&mutex);
		pthread_cond_wait(&notempty,&mutex);
		sem_p(semid, 0);
		printf("%d------------shm_lock------------------\n",++i);
		*pmyEnv = myEnv;
	
	    printf("shm_refresh:%uF,%uF,%u%%,%u%%,%um/(s*s),%um/(s*s),%um/(s*s),%uLUX,%umV,%umV\n", pmyEnv->temp[0], pmyEnv->temp[1], pmyEnv->hum[0], pmyEnv->hum[1], pmyEnv->x, pmyEnv->y, pmyEnv->z, pmyEnv->ill, pmyEnv->bet, pmyEnv->adc);
		printf("shm_refresh success!!\n");
		sem_v(semid, 0);
		pthread_mutex_unlock(&mutex);	
		
	}

}



